import pandas as pd

import numpy as np

from sklearn.preprocessing import StandardScaler

from sklearn.model_selection import train_test_split

import matplotlib.pyplot as plt

def main():

    """读入数据"""
    df_wine = pd.read_csv('./3.1/wine/wine.data', header=None) # 本地加载

    # df_wine=pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data',header=None)#服务器加载

    # print((df_wine))
    """取其中类别标签为一类和二类的白酒数据生成新的白酒数据"""
    df_wine =  df_wine.drop(index = df_wine[(df_wine[0] == 3)].index.tolist())

    # print((df_wine))
    # df_wine[(df_wine['0'] == 0)].index.tolist() 
    # df_wine.drop("3",axis = 0)
    # lable = df_wine.iloc[:, 0]
    # print(type(lable))

    # 把分类属性与常规属性分开
    x, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values
    print(x)

    # split the data，train：test=7:3
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, stratify=y, random_state=0)


    """数据标准化（规范化）"""
    # standardize the feature 标准化单位方差

    sc = StandardScaler()

    x_train_std = sc.fit_transform(x_train)

    x_test_std = sc.fit_transform(x_test)

    # print(x_train_std)

    """主成分分析PCA"""

    # 构造协方差矩阵
    cov_matrix = np.cov(x_train_std.T)

    #求协方差矩阵的特征值和特征向量
    eigen_val, eigen_vec = np.linalg.eig(cov_matrix)

    # 特征变换

    eigen_pairs = [(np.abs(eigen_val[i]), eigen_vec[:, i]) for i in range(len(eigen_val))]

    eigen_pairs.sort(key=lambda k: k[0], reverse=True) # (特征值，特征向量)降序排列

    # print(eigen_pairs)

    w = np.hstack((eigen_pairs[0][1][:, np.newaxis], eigen_pairs[1][1][:, np.newaxis])) # 降维投影矩阵W

    # print(w)

    x_train_pca = x_train_std.dot(w)

    # print(x_train_pca)

    color = ['r', 'g', 'b']

    marker = ['s', 'x', 'o']

    for l, c, m in zip(np.unique(y_train), color, marker):
        print(l)
        plt.scatter(x_train_pca[y_train == l, 0],x_train_pca[y_train == l, 1],c=c, label=l, marker=m)

    plt.title('PCA')

    plt.xlabel('PC1')

    plt.ylabel('PC2')

    plt.legend(loc='lower left')

    plt.show()

if __name__ == '__main__':
    main()
